<template>
  <el-popover v-model="visible" placement="bottom" :width="width" trigger="click" :disabled="disabled">
    <template v-slot:reference >
      <span class="svg-container fty-button " :class="disabled ? 'button-disabled' : 'button-primary'">
      <svg-icon icon-class="funnel" />
    </span>
    </template>
    <div class="popover-setting">
      <h2 class="mb-3 mt-2" style="width: 100%; font-size: 1.2em; text-align: center;">{{ $t('dashboard.filter_settings') }}</h2>

      <div v-if="dateFilter" class="filter-title flex justify-between">
        <span>{{ $t('modules.data_center.device_analyze.date_unit') }}: </span>
        <div class="set-value">
          <template>
            <el-radio v-for="obj in dateFilterData" :key="obj.value" v-model="config.dateUnit" :label="obj.value" @change="changeDateUnit"> {{ obj.label }}</el-radio>
          </template>
        </div>
      </div>

      <div v-if="dateFilter" class="filter-title flex justify-between">
        <span>{{ $t('modules.data_center.device_analyze.date_range') }}: </span>
        <div class="set-value">
          <template>
            <el-radio v-for="(range) in getDateRange(config.dateUnit)" :key="range" v-model="config.dateRange" :label="range">{{ range }} {{ config.dateUnit }}</el-radio>
          </template>
        </div>
      </div>

      <div v-if="modelFilter" class="filter-title flex justify-between">
        <span>{{ $t('dashboard.model') }}: </span>
        <div class="set-value">
          <template>
            <el-checkbox v-model="config.allModels" :label="'ALL'"><span>{{ $t('common.all') }}</span></el-checkbox>
          </template>
        </div>
      </div>

      <el-checkbox-group v-if="modelFilter && !config.allModels" v-model="configModels">
        <div v-for="model in models_inte" v-if="modelFilter" :key="model" class="list-group-item">
          <span><el-checkbox :label="model">{{ model }}</el-checkbox></span>
        </div>
      </el-checkbox-group>

      <div v-if="appsFilter" class="filter-title flex justify-between">
        <span>Applications: </span>
        <div class="set-value">
          <template>
            <el-checkbox v-model="config.allApps" :label="'ALL'"><span>{{ $t('common.all') }}</span></el-checkbox>
          </template>
        </div>
      </div>
      <el-checkbox-group v-if="appsFilter && !config.allApps" v-model="configApps">
        <div v-for="app in apps" :key="app.packageName" class="list-group-item">
          <el-checkbox :label="app.packageName">
            <span>{{ app.appName }}</span>
          </el-checkbox>
        </div>
      </el-checkbox-group>
      <div class="mt-3 text-right">
        <el-button size="small" type="primary" @click="returnConfig()">{{ $t('common.confirm') }}</el-button>
      </div>
    </div>
  </el-popover>
</template>

<script>
import { getDomainValue, setDomainValue } from './local-storage-util'
import {
  selectAllModel
} from '@/api/dashboard'

export default {
  name: 'ChartDataFilter',
  props: {
    width: {
      type: Number,
      default: 500
    },
    dateFilter: {
      type: Boolean,
      default: false
    },
    modelFilter: {
      type: Boolean,
      default: false
    },
    appsFilter: {
      type: Boolean,
      default: false
    },
    disabled: {
      type: Boolean,
      default: false
    },
    defaultConfig: {},
    domain: String,
    models: Array,
    apps: Array
  },

  component: [
    setDomainValue,
    getDomainValue
  ],
  data() {
    return {
      visible: false,
      config: {
      },
      configModels: [],
      configApps: [],
      // TODO 这里要改用合局获取的型号
      models_inte: [],
      apps_inte: []
    }
  },
  computed: {
    dateFilterData() {
      return [
        {
          'label': this.$t('common.day'),
          'value': 'Day',
          'range': [7, 14]
        },
        {
          'label': this.$t('common.month'),
          'value': 'Month',
          'range': [3, 6, 12]
        }
      ]
    }
  },
  mounted() {
    console.log('mounted')
    // this.width = this.width == undefined ? this._width : this._width
    if (this.domain === undefined) {
      alert('The domain parameter is not set')
      return
    }

    let defConfig = this.defaultConfig
    if (defConfig == null) {
      alert('default is null')
      defConfig = {}
    }
    // 如果因为外部数据变化，导致数据缺失的，则需要自动补齐；
    if (this.dateFilter) {
      if (!defConfig.dateUnit) {
        defConfig.dateUnit = 'Day'
      }
      if (!defConfig.dateRange) {
        defConfig.dateRange = 7
      }
    }
    if (this.modelFilter) {
      defConfig.allModels = true
      if (this.models && this.models.length > 0) {
        this.models_inte = []
        for (const m of this.models) {
          var tmp = {
            modelName: m.modelName,
            modelCode: m.modelCode
          }
          this.models_inte.push(tmp)
        }
      } else {
        selectAllModel().then((res) => {
          this.models_inte = res
        })
      }
      if (!defConfig.models || defConfig.models.length < 1) {
        defConfig.models = []
      }
    }
    if (this.appsFilter) {
      defConfig.allApps = true
      this.config.allApps = true
      console.log('不勾选All框', (this.appsFilter && !this.config.allApps))
      console.log('勾选All框', (this.config.allApps))
      console.log(this.apps)
      if (this.apps && this.apps.length > 0) {
        this.apps_inte = []
        for (const a of this.apps) {
          var tmp = {
            appFileId: a.appFileId,
            appName: a.appName,
            packageName: a.packageName,
            iconUrl: a.iconUrl
          }
          this.apps_inte.push(tmp)
        }
      }
    }

    const rootNode = this.$store.getters['pageSettings']
    this.config = getDomainValue(rootNode, this.domain, defConfig)
    this.configApps = this.config.apps ? this.config.apps : []
    this.configModels = this.config.models ? this.config.models : []
    this.$emit('confirm', this.config)
  },
  methods: {
    changeDateUnit(dateUnit) {
      if (dateUnit === 'Day') {
        this.config.dateRange = 7
      } else if (dateUnit === 'Month') {
        this.config.dateRange = 6
      } else {
        this.config.dateRange = undefined
      }
    },
    returnConfig() {
      if (this.dateFilter) {
        if (!this.config.dateUnit) {
          this.$message({
            message: '$t{common.message.please_choose_date_unit}',
            type: 'error'
          })
          // alert('请选择日期单位(改用标准的弹出错误框）')
          return
        }
        if (!this.config.dateRange) {
          this.$message({
            message: '$t{common.message.please_choose_date_range}',
            type: 'error'
          })
          return
        }
      }
      if (this.modelFilter) {
        var modelList = []
        for (const m of this.configModels) {
          for (const t of this.models_inte) {
            if (t === m) {
              modelList.push(m)
            }
          }
        }
        if (!this.config.allModels && modelList.length < 1) {
          this.$message({
            message: this.$t('device.model_select_tip'),
            type: 'error'
          })
          return
        }
        this.config.models = modelList
      }
      if (this.appsFilter) {
        var appPKNameList = []
        for (const pkName of this.configApps) {
          for (const app of this.apps) {
            if (app.packageName == pkName) {
              appPKNameList.push(pkName)
            }
          }
        }
        if (!this.config.allApps && appPKNameList.length < 1) {
          this.$message({
            message: this.$t('common.message.please_choose_a_application'),
            type: 'error'
          })
          return
        }
        this.config.apps = appPKNameList
      }
      setDomainValue(this.domain, this.config)
      this.$emit('confirm', this.config)
      this.visible = false
    },
    getDateRange(dateUnit) {
      if (dateUnit === undefined) {
        return []
      }
      for (let i = 0; i < this.dateFilterData.length; i++) {
        if (this.dateFilterData[i].value === dateUnit) {
          return this.dateFilterData[i].range
        }
      }
      return []
    }
  }
}
</script>
<style scoped lang="scss">
  .filter-title {
    padding: 12px 5px;
    border-bottom: 1px solid #edf2f9;
    font-weight: 500;
  }
  .el-checkbox-group {
    padding: 0px;
    .list-group-item {
      padding: 8px 10px;
      border-bottom: 1px solid #edf2f9;
      /*&:last-of-type  {*/
      /*border-bottom: 0px;*/
      /*}*/
      &:hover {
        background-color: #edf2f9;
      }
    }
  }

</style>
